<template>
  <view>
    <view class="header">
      <view class="title">编辑收货地址</view>
      <view class="save" @click="saveAddress">保存</view>
    </view>
    <view class="address-item">
      <view class="label">所在城市:</view>
      <input class="content" v-model="address.city" />
    </view>
    <view class="address-item">
      <view class="label">小区/大厦/学校:</view>
      <input class="content" v-model="address.department" />
    </view>
    <view class="address-item">
      <view class="label">楼号 - 门牌号:</view>
      <input class="content" v-model="address.houseNumber" />
    </view>
    <view class="address-item">
      <view class="label">收货人:</view>
      <input class="content" v-model="address.name" />
    </view>
    <view class="address-item">
      <view class="label">联系电话:</view>
      <input class="content" v-model="address.phone" type="number" />
    </view>
  </view>
</template>

<script>
import config from '../config.js';
export default {
  data() {
    return {
      address: {}
    };
  },
  onLoad(options) {
    const addressId = options.id;
    if (addressId) {
      uni.request({
        url:config.api_host+ `/address/${addressId}`, // 假设接口支持根据id获取地址，需调整为实际接口
        success: (res) => {
          if (res.data) {
            this.address = res.data;
          }
        },
        fail: (err) => {
          console.error('获取地址信息失败:', err);
        }
      });
    }
  },
  methods: {
    saveAddress() {
      // 验证数据完整性，这里简单验证，可根据需求扩展
      if (!this.address.city ||!this.address.department ||!this.address.name ||!this.address.phone) {
        uni.showToast({
          title: '请填写完整的地址信息',
          icon: 'none'
        });
        return;
      }

      uni.request({
        url: config.api_host+`/address/${this.address.id}`,
        method: 'PUT',
        data: this.address,
        success: (res) => {
          
          uni.showToast({
            title: '地址保存成功',
            icon:'success'
          });
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/dingdan/adress`
            });
          }, 1000);
        },
        fail: (err) => {
          console.error('保存地址失败:', err);
          uni.showToast({
            title: '地址保存失败',
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.save {
  font-size: 16px;
  color: #007aff;
  cursor: pointer;
}
.address-item {
  padding: 10px;
  border-bottom: 1px solid #ebe8e8;
  display: flex;
  align-items: center;
}
.label {
  width: 100px;
  color: #666;
}
.content {
  flex: 1;
  color: #333;
  border-radius: 4px;
  padding: 5px;
}
</style>